#include <iostream>
#include "Poco/UUID.h"
#include "Poco/UUIDGenerator.h"
#include "Poco/Exception.h"
#include "Guid.h"

using namespace SystemTool;

// Create default uuid
Guid Guid::CreateByRandom()
{
    Poco::UUIDGenerator Generator;
    Poco::UUID id = Generator.create();

    Guid FinalId;
    char* pSrcId = (char*)&id;
    char* pDestId = (char*)&FinalId;
    memcpy(pDestId, pSrcId, sizeof(Guid));
    return FinalId;
}

// Create an uuid from a string
Guid Guid::FromString(std::string strUuid)
{
    Guid FinalId;
 
    if(strUuid.empty())
    {
        return FinalId;
    }

    try
    {
        Poco::UUID id;
        id.parse(strUuid);

        char *pSrcId = (char *)&id;
        char *pDestId = (char *)&FinalId;
        memcpy(pDestId, pSrcId, sizeof(Guid));
    }
    catch (const Poco::Exception &e)
    {
        std::cout << "Err Happend:" << e.displayText() << std::endl;
    }
    return FinalId;
}

// Copy from the buffer
Guid Guid::CopyFrom(char *pBuffer)
{
    Guid FinalId;
 
    if(pBuffer == nullptr)
    {
        return FinalId;
    }

    try
    {
        Poco::UUID id;
        id.copyFrom(pBuffer);

        char *pSrcId = (char *)&id;
        char *pDestId = (char *)&FinalId;
        memcpy(pDestId, pSrcId, sizeof(Guid));
    }
    catch (const Poco::Exception &e)
    {
        std::cout << "Err Happend:" << e.displayText() << std::endl;
    }
    return FinalId;
}

// Copy to the buffer
void Guid::CopyTo(char *pBuffer)
{
    if(pBuffer == nullptr)
    {
        return;
    }

    try
    {
       
        char *pSrcId = (char *)this;
        Poco::UUID DestID;
        char *pDestId = (char *)&DestID;
        memcpy(pDestId, pSrcId, sizeof(Guid));

        DestID.copyTo(pBuffer);
    }
    catch (const Poco::Exception &e)
    {
        std::cout << "Err Happend:" << e.displayText() << std::endl;
    }
}

// Uuid to string
std::string Guid::ToString()
{
    Poco::UUID DestId;
    char* pSrcId = (char*)this;
    char* pDestId = (char*)&DestId;
    memcpy(pDestId, pSrcId, sizeof(Guid));

    return DestId.toString();
}
